﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.HSSF.Model;
using Org.BouncyCastle.Asn1.Ocsp;
using S.Authorization.Common;
using S.Authorization.Common.Dto;
using S.Authorization.Domain.Model.Authority;
using S.Authorization.Domain.Model.Organization;
using S.Authorization.Domain.SqlServer;
using S.Authorization.Read.API.Application.Command.OrganizationCommand;
using S.Common.Enums.Organization;
using static S.Authorization.Read.API.Application.Command.RoleCommand.RoleReadAllCommand;

namespace S.Authorization.Read.API.Controllers.Organization
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        private IMediator mediator;
        private readonly SqlDbContext db;

        public DepartmentController(IMediator mediator,SqlDbContext _db )
        {
            this.mediator = mediator;
            this.db = _db;
        }
        /// <summary>
        /// 部门树显示
        /// </summary>
        /// <returns></returns>
        [HttpGet("DepartmentList")]
        public async Task<IActionResult> DepartmentList(int PID)
        {
            return Ok(await mediator.Send(new DepartmentListCommand() { PID = PID }));
        }
        /// <summary>
        /// 部门显示
        /// </summary>
        /// <param name="PID"></param>
        /// <returns></returns>
        [HttpGet("DepartmentShow")]
        public async Task<IActionResult> DepartmentShow()
        {
            return Ok(await mediator.Send(new DepartMentShowCommand() { }));
        }
        private string CalculateFullName(DepartmentModel department)
        {
            var fullName = department.IndustryTitle;

            while (department.PID != 0)
            {
                department = db.DepartmentModel.FirstOrDefault(d => d.DepartMentId == department.PID);

                if (department != null)
                {
                    fullName = department.IndustryTitle + "/" + fullName;
                }
                else
                {
                    // 处理找不到上级部门的情况
                    break;
                }
            }

            return fullName;
        }
        /// <summary>
        /// 部门行转列
        /// </summary>
        /// <returns></returns>
        [HttpGet("RowDenormaliser")]
        public async Task<IActionResult> RowDenormaliser(int pageIndex,int pageSieze, string? IndustryTitle, bool? state)
        {
            int totalCount = 0;
            int pageCount = 0;
            // 配置 AutoMapper 映射关系
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<DepartmentModel, DepartDto>()
                    .ForMember(dest => dest.full_name, opt => opt.MapFrom(src => CalculateFullName(src)));
            });
            var mapper = config.CreateMapper();
            var query = await db.DepartmentModel.FromSqlRaw(@"
                WITH department_tree AS (
    -- 基础情况：选择所有顶级部门
    SELECT 
        DepartmentId, 
        IndustryTitle, 
        PID, 
        CAST(IndustryTitle AS varchar(100)) AS full_name, 
        CreateBy, 
        CreateTime, 
        IsDel, 
        UpdateBy, 
        UpdateTime,
        SerialNumber,
        DepartTypeEnum
    FROM DepartmentModel
    WHERE PID = 0 -- 选择所有顶级部门

    UNION ALL

    -- 递归情况：选择子部门
    SELECT 
        d.DepartmentId, 
        d.IndustryTitle, 
        d.PID, 
        CAST(CONCAT(dt.full_name, '/', d.IndustryTitle) AS varchar(100)), 
        d.CreateBy, 
        d.CreateTime, 
        d.IsDel, 
        d.UpdateBy, 
        d.UpdateTime,
        d.SerialNumber,
        d.DepartTypeEnum
    FROM DepartmentModel d
    INNER JOIN department_tree dt ON d.PID = dt.DepartmentId
)
-- 这里我们添加一个ORDER BY来确保结果按照某种逻辑顺序（例如按照full_name）进行排序
SELECT * FROM department_tree ORDER BY full_name;
                ").ToListAsync();
            var dtoList = mapper.Map<List<DepartDto>>(query);
            if(!string.IsNullOrEmpty(IndustryTitle))
            {
                dtoList = dtoList.Where(x => x.IndustryTitle.Contains(IndustryTitle)).ToList();
            }
            if(!string.IsNullOrEmpty(state.ToString()))
            {
                dtoList = dtoList.Where(x => x.IsDel == state).ToList();
            }
            totalCount = dtoList.Count();
            pageCount = (int)Math.Ceiling(totalCount * 1.0 / pageSieze);
            dtoList = dtoList.OrderBy(x => x.DepartmentId).Skip((pageIndex - 1) * pageSieze).Take(pageSieze).ToList();
            return Ok(new { dtoList ,totalCount,pageCount});
        }
        /// <summary>
        /// 部门分页显示加组合查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        [HttpGet("GetPageDepartment")]
        public async Task<Pager<DepartmentModel>> GetPageDepartment(int pageIndex, int pageSize, string? IndustryTitle,bool? state)
        {
            return await mediator.Send(new DepartMentPageAllCommand()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                IndustryTitle = IndustryTitle,
                state=state
            });
        }
        /// <summary>
        /// 部门类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetDepartType")]
        public List<object> GetDepartType()
        {
            List<object> list = new List<object>();
            foreach (var item in Enum.GetValues<DepartTypeEnum>())
            {
                list.Add(new
                {
                    name = item.ToString(),
                    value = item,
                });
            }
            return list;
        }
    }
}
